package com.brk.socket.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.brk.socket.common.ResultCodeEnum;
import com.brk.socket.entity.User;
import com.brk.socket.entity.UserDTO;
import com.brk.socket.exception.MyException;
import com.brk.socket.mapper.UserMapper;
import com.brk.socket.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author brk
 * @date 2023/7/17 14:40
 * @Description:
 */
@Component
public class LoginIdentityInterceptor implements HandlerInterceptor {

    @Autowired
    UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if(token == null || token.trim().length() == 0) {
            throw new MyException(ResultCodeEnum.TOKEN_ILLEGAL);
        }
        User user = JwtUtil.unsign(token, User.class);
        if(user == null) {
            throw new MyException(ResultCodeEnum.TOKEN_ILLEGAL);
        }

        User check = userMapper.selectOne(new QueryWrapper<User>().eq("email", user.getEmail()).eq("password", user.getPassword()));

        if(check == null) {
            throw new MyException(ResultCodeEnum.TOKEN_ILLEGAL);
        }

        return true;

    }
}
